import { randomUUID } from 'crypto'
/**
 * add record to a domain
 */
export default defineEventHandler(async (event) => {
  const name = getRouterParam(event, 'name')
  const body = await readBody<RRecord>(event)
  const data = await useStorage().getItem<Domain>(`first:domain:${name}`)
  if (data === null) {
    // TODO: error handle.
    return 'emm'
  }
  const records = data.records || []
  console.log('server side add record', records)
  const dup = records.find((r) => r.origin === body.origin && r.data === body.data)
  console.log('body', body, 'dup', dup)
  if (dup) {
    // TODO: duplicate
    return 'dup'
  }
  body.uuid = randomUUID()
  records.push(body)
  data.records = records
  await useStorage().setItem(`first:domain:${name}`, data)
  return 'success'
})
